<template>
  <div class="qrcode-img" ref="qrcodeImg">
    <div class="form-title">{{ props.shareInfo.title }}</div>
    <div class="source-name" v-show="props.shareInfo.showName">{{ props.shareInfo.sourceName }}</div>
    <div class="form-qrcode">
      <img :src="qrCodeUrl" alt="" />
    </div>
    <div class="form-tip">微信扫码或长按识别，填写内容</div>
  </div>
</template>
<script setup>
import { ref, defineProps, defineExpose, reactive, watch } from 'vue'
import QRCode from 'qrcode'
import html2canvas from 'html2canvas'

const props = defineProps({
  shareInfo: {
    type: Object
  }
})
//生成二维码
const options = reactive({
  margin: 0
})
const qrCodeUrl = ref('')
const generateQRCode = async () => {
  if(!props.shareInfo.link) return
  try {
    qrCodeUrl.value = await QRCode.toDataURL(props.shareInfo.link, options)
  } catch (error) {
    console.error('生成二维码失败', error);
  }
}
watch(() => props.shareInfo.link,() => {
  generateQRCode()
},{deep:true,immediate:true})
//下载二维码
const qrcodeImg = ref(null)
const downloadQrcodeImg = () => {
  const options = {
    scale: 2, // 将画布分辨率提高一倍
  }
  html2canvas(qrcodeImg.value, options).then(canvas => {
    const imageData = canvas.toDataURL("image/png");
    const downloadLink = document.createElement('a');
    downloadLink.href = imageData;
    downloadLink.download = '问卷二维码.png';
    downloadLink.click();
  })
}
defineExpose({
  downloadQrcodeImg
})
</script>

<style lang="scss" scoped>
.qrcode-img {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
  border: 1px solid #e4e4e4;
  border-radius: 8px;

  .form-title {
    margin-bottom: 10px;
    text-align: center;
  }

  .source-name {
    margin-bottom: 10px;
    padding: 5px 10px;
    background: #e7f4ff;
    border-radius: 4px;
  }

  .form-qrcode {
    margin-bottom: 10px;
    width: 120px;
    height: 120px;

    img {
      width: 100%;
      height: 100%;
      background: #797979;
    }
  }

  .form-tip {
    white-space: nowrap;
    text-align: center;
    font-size: 12px;
    color: #aaaaaa;
  }
}

.bottom-switch {
  display: flex;
  justify-content: space-between;
  padding: 20px 10px;
  border-top: 1px solid #aaaaaa;
}
</style>